package com.os.meituan.common;


import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;


public class WebClass {

    /**
     * 此方法只能标准化整个URL，并不适合于单独编码参数值
     */
    public static String encodeURL(String url) {
        try {
            var str = URLEncoder.encode(url, "UTF-8");
            str = str.replaceAll("\\+", "%2B");
            return str;
        } catch (UnsupportedEncodingException e) {
            return "";
        }
    }

    public static HttpServletRequest getRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        return request;
    }

    public static HttpServletResponse getResponse() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletResponse response = attributes.getResponse();
        return response;
    }

    // 考虑到可能用了反向代理，这里如果读取到本地ip，需要考虑从反向代理约定好header中读取代理前的ip


    // 把系统的某个文件给用户下载，如果浏览器支持，可以选择在线打开
    public static void downloadFile(String fileFullName, boolean isOnline) throws IOException {
        HttpServletResponse response = getResponse();
        File f = new File(fileFullName);
        if (!f.exists()) {
            System.out.println("找不到路径：" + fileFullName);
            response.sendError(404, "File not found!");
            return;
        }
        BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
        byte[] buf = new byte[1024];
        int len = 0;

        response.reset(); // 非常重要
        response.setHeader("Content-Length", "" + f.length());
        if (isOnline) { // 在线打开方式
            URL u = new URL("file:///" + fileFullName);
            response.setContentType(u.openConnection().getContentType());
            response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(f.getName(), "utf-8"));
            // 文件名应该编码成UTF-8
        } else { // 纯下载方式
            response.setContentType("application/x-msdownload");
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(f.getName(), "utf-8"));
        }
        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

    public static void downloadFile(String fileName, InputStream inputStream) throws IOException {
        var response = getResponse();
        var request = getRequest();

        BufferedInputStream br = new BufferedInputStream(inputStream);
        byte[] buf = new byte[1024];
        int len = 0;

        String userAgent = request.getHeader("user-agent").toLowerCase();
        if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");
        }

        response.reset(); // 非常重要
        response.setHeader("Content-Length", "" + inputStream.available());
        response.setContentType("application/x-msdownload");
        response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

        OutputStream out = response.getOutputStream();
        while ((len = br.read(buf)) > 0)
            out.write(buf, 0, len);
        br.close();
        out.close();
    }

    public static void downloadFile(String fileName, ByteArrayOutputStream outputStream) throws IOException {
        var inputStream = new ByteArrayInputStream(outputStream.toByteArray());
        downloadFile(fileName, inputStream);

    }

    // 考虑到可能用了反向代理，这里如果读取到host，需要考虑从反向代理约定好header中读取代理前的host


    // 获得基础请求地址
    public static String getBaseUri() {
        HttpServletRequest request = getRequest();
        String path = request.getContextPath();
        String baseUri = request.getScheme() + "://" + request.getServerName()
                + ":" + request.getServerPort() + path + "/";

        return baseUri;
    }

    // 页面跳转
    public static void sendRedirect(String url) {
        HttpServletResponse response = getResponse();
        try {
            response.sendRedirect(url);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String requestToString(String key) {
        HttpServletRequest request = getRequest();
        String va;
        va = request.getParameter(key);
        if (StringClass.isNullOrEmpty(va) || "null".equals(va) || "undefined".equals(va)) {
            return null;
        }

        return va;
    }

    public static int requestToInt(String key) {
        HttpServletRequest request = getRequest();
        String va;
        va = request.getParameter(key);
        if (StringClass.isNullOrEmpty(va) || "null".equals(va) || "undefined".equals(va)) {
            return 0;
        }
        try {
            return Integer.parseInt(va);
        } catch (Exception ex) {
            return 0;
        }
    }

    public static long requestToLong(String key) {
        HttpServletRequest request = getRequest();
        String va;
        va = request.getParameter(key);
        if (StringClass.isNullOrEmpty(va)) {

        }
        try {
            return Long.valueOf(va);
        } catch (Exception ex) {
            return 0;
        }
    }

}
    /**
     * 连接多个url地址，保证中间不会出现连续斜杠
     */
